package be.sc.classicnetwork.dao.hibernate;

import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.support.DataAccessUtils;

import be.sc.classicnetwork.dao.UserDao;
import be.sc.classicnetwork.model.User;

/**
 * User DAO Implementation.
 * 
 */
public class UserDaoImpl extends HibernateGenericDao<User> implements UserDao {

	/**
	 * 
	 */
	public UserDaoImpl() {
		super();
	}

	/**
	 * @param clazz
	 */
	public UserDaoImpl(Class<User> clazz) {
		super(clazz);
	}

	/**
	 * @see be.sc.classicnetwork.dao.hibernate.HibernateGenericDao#findByIdFull(int)
	 */
	@Override
	public User findByIdFull(String id) {
		User user = super.findByIdFull(id);

		// load roles
		getHibernateTemplate().initialize(user.getRoles());

		return user;
	}

	/**
	 * @see org.acegisecurity.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
	 */
	public UserDetails loadByUsername(String username)
			throws UsernameNotFoundException {
		// find the user by name
		User user = (User) DataAccessUtils
				.uniqueResult(findByCriteria(
						0,
						0,
						null,
						new Criterion[] { Restrictions.eq("username", username) },
						null));

		// load roles
		if (user != null) {
			getHibernateTemplate().initialize(user.getRoles());
		}

		return user;
	}
}
